<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RK3588硬件编码视频流测试</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { 
            font-family: "Microsoft YaHei", "Segoe UI", Arial, sans-serif; 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
        }
        
        .container { max-width: 1400px; margin: 0 auto; padding: 20px; }
        
        .header { 
            background: rgba(255,255,255,0.95);
            backdrop-filter: blur(10px);
            border-radius: 16px;
            padding: 25px;
            margin-bottom: 20px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .header h1 {
            background: linear-gradient(135deg, #667eea, #764ba2);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            font-size: 28px;
            font-weight: 700;
        }
        
        .status-info {
            display: flex;
            flex-direction: column;
            align-items: flex-end;
            gap: 8px;
        }
        
        .status { 
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 8px 16px;
            border-radius: 20px;
            font-weight: 600;
            font-size: 14px;
            transition: all 0.3s ease;
        }
        .status.online { 
            background: rgba(46, 204, 113, 0.1);
            color: #27ae60;
            border: 2px solid rgba(46, 204, 113, 0.3);
        }
        .status.offline { 
            background: rgba(231, 76, 60, 0.1);
            color: #e74c3c;
            border: 2px solid rgba(231, 76, 60, 0.3);
        }
        
        .status-dot {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background: currentColor;
        }
        .status.online .status-dot { 
            animation: pulse 2s infinite;
            box-shadow: 0 0 15px currentColor;
        }
        
        @keyframes pulse {
            0%, 100% { opacity: 1; transform: scale(1); }
            50% { opacity: 0.7; transform: scale(1.1); }
        }
        
        .current-time {
            font-size: 12px;
            color: #666;
            font-family: monospace;
        }
        
        .main-grid {
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: 20px;
            margin-bottom: 20px;
        }
        
        .video-section {
            background: rgba(255,255,255,0.95);
            backdrop-filter: blur(10px);
            border-radius: 16px;
            padding: 30px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.1);
        }
        
        .video-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 3px solid #667eea;
        }
        
        .video-header h2 {
            color: #2c3e50;
            font-size: 22px;
        }
        
        .stream-selector {
            padding: 10px 15px;
            border: 2px solid #ddd;
            border-radius: 8px;
            background: white;
            font-size: 14px;
            color: #2c3e50;
        }
        
        .video-container {
            position: relative;
            border-radius: 12px;
            overflow: hidden;
            background: #000;
            box-shadow: 0 8px 24px rgba(0,0,0,0.2);
        }
        
        .video { 
            width: 100%; 
            height: 450px; 
            object-fit: cover;
            display: block;
        }
        
        .video-placeholder {
            height: 450px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: linear-gradient(45deg, #1a1a1a, #2d2d2d);
            color: #888;
            text-align: center;
        }
        
        .placeholder-content {
            animation: fadeIn 1s ease-in-out;
        }
        
        .placeholder-content h3 {
            font-size: 24px;
            margin-bottom: 15px;
            color: #667eea;
        }
        
        .placeholder-content p {
            font-size: 16px;
            opacity: 0.8;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .controls {
            display: flex;
            gap: 12px;
            justify-content: center;
            margin-top: 20px;
        }
        
        .info-panel {
            background: rgba(255,255,255,0.95);
            backdrop-filter: blur(10px);
            border-radius: 16px;
            padding: 30px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.1);
        }
        
        .info-panel h3 {
            color: #2c3e50;
            margin-bottom: 25px;
            font-size: 20px;
            border-bottom: 3px solid #667eea;
            padding-bottom: 10px;
        }
        
        .info-grid {
            display: grid;
            gap: 15px;
        }
        
        .info-item { 
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            padding: 18px; 
            border-radius: 12px;
            text-align: center;
            border-left: 5px solid #667eea;
            transition: all 0.3s ease;
        }
        
        .info-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.1);
        }
        
        .info-item strong {
            display: block;
            color: #2c3e50;
            font-size: 13px;
            margin-bottom: 8px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .info-item span {
            font-size: 18px;
            font-weight: 700;
            color: #667eea;
        }
        
        .charts-section {
            background: rgba(255,255,255,0.95);
            backdrop-filter: blur(10px);
            border-radius: 16px;
            padding: 30px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.1);
        }
        
        .charts-section h3 {
            color: #2c3e50;
            margin-bottom: 25px;
            font-size: 22px;
            border-bottom: 3px solid #667eea;
            padding-bottom: 10px;
        }
        
        .charts-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 25px;
        }
        
        .chart-container {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.05);
        }
        
        .chart-container h4 {
            color: #2c3e50;
            margin-bottom: 15px;
            font-size: 16px;
            text-align: center;
        }
        
        .chart {
            width: 100%;
            height: 280px;
        }
        
        .btn { 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white; 
            border: none; 
            padding: 14px 28px; 
            border-radius: 30px; 
            cursor: pointer; 
            font-weight: 600;
            font-size: 14px;
            transition: all 0.3s ease;
            box-shadow: 0 6px 20px rgba(102, 126, 234, 0.3);
        }
        
        .btn:hover { 
            transform: translateY(-3px);
            box-shadow: 0 10px 30px rgba(102, 126, 234, 0.4);
        }
        
        .btn:active {
            transform: translateY(-1px);
        }
        
        .btn.success {
            background: linear-gradient(135deg, #2ecc71 0%, #27ae60 100%);
            box-shadow: 0 6px 20px rgba(46, 204, 113, 0.3);
        }
        
        .btn.warning {
            background: linear-gradient(135deg, #f39c12 0%, #e67e22 100%);
            box-shadow: 0 6px 20px rgba(243, 156, 18, 0.3);
        }
        
        @media (max-width: 1200px) {
            .charts-grid { grid-template-columns: 1fr; }
        }
        
        @media (max-width: 768px) {
            .main-grid { grid-template-columns: 1fr; }
            .controls { flex-wrap: wrap; }
            .btn { padding: 12px 20px; font-size: 13px; }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>RK3588硬件编码视频流测试系统</h1>
            <div class="status-info">
                <div class="status offline" id="connectionStatus">
                    <div class="status-dot"></div>
                    <span id="statusText">离线</span>
                </div>
                <div class="current-time" id="currentTime"></div>
            </div>
        </div>

        <div class="main-grid">
            <div class="video-section">
                <div class="video-header">
                    <h2>实时视频流</h2>
                    <select class="stream-selector" id="streamType">
                        <option value="mjpeg">MJPEG 视频流</option>
                        <option value="h264">H.264 硬件编码</option>
                    </select>
                </div>
                
                <div class="video-container">
                    <img id="videoElement" class="video" style="display: none;">
                    <div id="videoPlaceholder" class="video-placeholder">
                        <div class="placeholder-content">
                            <h3>RK3588视频流</h3>
                            <p>等待设备连接...</p>
                            <div style="margin-top: 20px;">
                                <div class="status offline">
                                    <div class="status-dot"></div>
                                    <span>等待连接</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="controls">
                    <button class="btn" onclick="refreshVideo()">刷新视频</button>
                    <button class="btn success" onclick="testConnection()">测试连接</button>
                    <button class="btn warning" onclick="toggleFullscreen()">全屏模式</button>
                </div>
            </div>

            <div class="info-panel">
                <h3>实时状态监控</h3>
                <div class="info-grid">
                    <div class="info-item">
                        <strong>RK3588连接</strong>
                        <span id="connectionState">未连接</span>
                    </div>
                    <div class="info-item">
                        <strong>视频协议</strong>
                        <span id="protocolInfo">Unknown</span>
                    </div>
                    <div class="info-item">
                        <strong>编码格式</strong>
                        <span id="codecInfo">Unknown</span>
                    </div>
                    <div class="info-item">
                        <strong>视频分辨率</strong>
                        <span id="resolutionInfo">Unknown</span>
                    </div>
                    <div class="info-item">
                        <strong>帧率</strong>
                        <span id="fpsInfo">0 fps</span>
                    </div>
                    <div class="info-item">
                        <strong>视频码率</strong>
                        <span id="bitrateInfo">Unknown</span>
                    </div>
                    <div class="info-item">
                        <strong>传输延迟</strong>
                        <span id="latencyInfo">Unknown</span>
                    </div>
                    <div class="info-item">
                        <strong>最后更新</strong>
                        <span id="lastUpdateInfo">--</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- ECharts性能监控图表 -->
        <div class="charts-section">
            <h3>RK3588性能监控图表</h3>
            <div class="charts-grid">
                <div class="chart-container">
                    <h4>帧率实时监控</h4>
                    <div id="fpsChart" class="chart"></div>
                </div>
                <div class="chart-container">
                    <h4>延迟实时监控</h4>
                    <div id="latencyChart" class="chart"></div>
                </div>
                <div class="chart-container">
                    <h4>连接状态统计</h4>
                    <div id="connectionChart" class="chart"></div>
                </div>
                <div class="chart-container">
                    <h4>系统负载监控</h4>
                    <div id="systemChart" class="chart"></div>
                </div>
            </div>
        </div>
    </div>

    <!-- JavaScript库 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.7.2/socket.io.js"></script>
    <script src="{{ url_for('static', filename='echarts.min.js') }}"></script>
    
    <script>
        // WebSocket连接
        const socket = io();
        
        // ECharts图表实例
        let charts = {
            fps: null,
            latency: null,
            connection: null,
            system: null
        };
        
        // 数据存储
        let performanceData = {
            timestamps: [],
            fpsData: [],
            latencyData: [],
            connectionData: []
        };
        
        // 初始化ECharts图表
        function initCharts() {
            // FPS图表
            charts.fps = echarts.init(document.getElementById('fpsChart'));
            charts.fps.setOption({
                title: { text: '帧率 (FPS)', textStyle: { color: '#2c3e50', fontSize: 14 } },
                tooltip: { trigger: 'axis' },
                grid: { left: '10%', right: '5%', bottom: '15%', top: '20%' },
                xAxis: { 
                    type: 'category', 
                    data: [],
                    axisLabel: { fontSize: 10, color: '#666' }
                },
                yAxis: { 
                    type: 'value',
                    name: 'FPS',
                    axisLabel: { fontSize: 10, color: '#666' }
                },
                series: [{
                    name: '帧率',
                    type: 'line',
                    data: [],
                    smooth: true,
                    lineStyle: { color: '#2ecc71', width: 3 },
                    areaStyle: { color: 'rgba(46, 204, 113, 0.1)' },
                    symbol: 'circle',
                    symbolSize: 6
                }]
            });
            
            // 延迟图表
            charts.latency = echarts.init(document.getElementById('latencyChart'));
            charts.latency.setOption({
                title: { text: '延迟 (ms)', textStyle: { color: '#2c3e50', fontSize: 14 } },
                tooltip: { trigger: 'axis' },
                grid: { left: '10%', right: '5%', bottom: '15%', top: '20%' },
                xAxis: { 
                    type: 'category', 
                    data: [],
                    axisLabel: { fontSize: 10, color: '#666' }
                },
                yAxis: { 
                    type: 'value',
                    name: 'ms',
                    axisLabel: { fontSize: 10, color: '#666' }
                },
                series: [{
                    name: '延迟',
                    type: 'line',
                    data: [],
                    smooth: true,
                    lineStyle: { color: '#e74c3c', width: 3 },
                    areaStyle: { color: 'rgba(231, 76, 60, 0.1)' },
                    symbol: 'circle',
                    symbolSize: 6
                }]
            });
            
            // 连接状态饼图
            charts.connection = echarts.init(document.getElementById('connectionChart'));
            charts.connection.setOption({
                title: { text: '连接状态', textStyle: { color: '#2c3e50', fontSize: 14 } },
                tooltip: { trigger: 'item' },
                series: [{
                    name: '连接状态',
                    type: 'pie',
                    radius: '70%',
                    center: ['50%', '60%'],
                    data: [
                        { value: 1, name: '在线', itemStyle: { color: '#2ecc71' } },
                        { value: 0, name: '离线', itemStyle: { color: '#e74c3c' } }
                    ]
                }]
            });
            
            // 系统信息仪表盘
            charts.system = echarts.init(document.getElementById('systemChart'));
            charts.system.setOption({
                title: { text: '系统状态', textStyle: { color: '#2c3e50', fontSize: 14 } },
                series: [{
                    name: 'FPS',
                    type: 'gauge',
                    radius: '80%',
                    center: ['50%', '60%'],
                    min: 0,
                    max: 30,
                    detail: {
                        formatter: '{value} fps',
                        fontSize: 14
                    },
                    data: [{ value: 0, name: '当前帧率' }],
                    itemStyle: { color: '#667eea' }
                }]
            });
        }
        
        // 更新图表数据
        function updateCharts(data) {
            const timestamp = new Date().toLocaleTimeString();
            
            // 限制数据点数量
            if (performanceData.timestamps.length >= 20) {
                performanceData.timestamps.shift();
                performanceData.fpsData.shift();
                performanceData.latencyData.shift();
                performanceData.connectionData.shift();
            }
            
            performanceData.timestamps.push(timestamp);
            performanceData.fpsData.push(data.fps || 0);
            
            // 解析延迟
            let latencyValue = 0;
            if (data.latency && data.latency !== 'Unknown') {
                const match = data.latency.match(/(\d+)/);
                if (match) latencyValue = parseInt(match[1]);
            }
            performanceData.latencyData.push(latencyValue);
            performanceData.connectionData.push(data.connected ? 1 : 0);
            
            // 更新图表
            if (charts.fps) {
                charts.fps.setOption({
                    xAxis: { data: performanceData.timestamps },
                    series: [{ data: performanceData.fpsData }]
                });
            }
            
            if (charts.latency) {
                charts.latency.setOption({
                    xAxis: { data: performanceData.timestamps },
                    series: [{ data: performanceData.latencyData }]
                });
            }
            
            if (charts.connection) {
                const onlineCount = performanceData.connectionData.filter(s => s === 1).length;
                const offlineCount = performanceData.connectionData.length - onlineCount;
                
                charts.connection.setOption({
                    series: [{
                        data: [
                            { value: onlineCount, name: '在线' },
                            { value: offlineCount, name: '离线' }
                        ]
                    }]
                });
            }
            
            if (charts.system) {
                charts.system.setOption({
                    series: [{ data: [{ value: data.fps || 0, name: '当前帧率' }] }]
                });
            }
        }
        
        // WebSocket事件处理
        socket.on('connect', () => {
            console.log('[WebSocket] 连接成功');
        });
        
        socket.on('video_update', (data) => {
            console.log('[视频] 收到视频数据:', data);
            updateVideoStatus(data);
            updateCharts(data);
        });
        
        socket.on('connection_update', (data) => {
            console.log('[连接] 状态更新:', data);
            updateConnectionStatus(data.connected);
        });
        
        // 更新视频状态
        function updateVideoStatus(data) {
            const videoEl = document.getElementById('videoElement');
            const placeholderEl = document.getElementById('videoPlaceholder');
            
            console.log('[调试] 视频状态更新:', {
                connected: data.connected, 
                status: data.status, 
                protocol: data.protocol
            });
            
            // 修复显示条件：只要设备连接且有视频协议就显示
            if (data.connected && (data.status === 'online' || data.protocol === 'MJPEG' || data.protocol === 'H.264')) {
                // 显示视频
                console.log('[视频] 开始显示视频流');
                videoEl.src = '/video_proxy?t=' + Date.now();
                videoEl.style.display = 'block';
                placeholderEl.style.display = 'none';
                
                // 添加加载和错误处理
                videoEl.onload = function() {
                    console.log('[视频] 视频流加载成功');
                };
                videoEl.onerror = function() {
                    console.log('[视频] 视频流加载失败，回退到占位符');
                    videoEl.style.display = 'none';
                    placeholderEl.style.display = 'flex';
                };
            } else {
                // 隐藏视频
                console.log('[视频] 隐藏视频流 - 条件不满足');
                videoEl.style.display = 'none';
                placeholderEl.style.display = 'flex';
            }
            
            // 更新信息面板
            document.getElementById('connectionState').textContent = data.connected ? '已连接' : '未连接';
            document.getElementById('protocolInfo').textContent = data.protocol || 'Unknown';
            document.getElementById('codecInfo').textContent = data.codec || 'Unknown';
            document.getElementById('resolutionInfo').textContent = data.resolution || 'Unknown';
            document.getElementById('fpsInfo').textContent = (data.fps || 0) + ' fps';
            document.getElementById('bitrateInfo').textContent = data.bitrate || 'Unknown';
            document.getElementById('latencyInfo').textContent = data.latency || 'Unknown';
            document.getElementById('lastUpdateInfo').textContent = data.last_update || '--';
        }
        
        // 更新连接状态
        function updateConnectionStatus(connected) {
            const statusEl = document.getElementById('connectionStatus');
            const statusText = document.getElementById('statusText');
            
            if (connected) {
                statusEl.className = 'status online';
                statusText.textContent = '在线';
            } else {
                statusEl.className = 'status offline'; 
                statusText.textContent = '离线';
            }
        }
        
        // 更新时间
        function updateTime() {
            document.getElementById('currentTime').textContent = 
                new Date().toLocaleString('zh-CN');
        }
        
        // 按钮功能
        function refreshVideo() {
            const videoEl = document.getElementById('videoElement');
            videoEl.src = '/video_proxy?t=' + Date.now();
            console.log('[操作] 刷新视频流');
        }
        
        function testConnection() {
            fetch('/api/status')
                .then(r => r.json())
                .then(data => {
                    const connected = data.video_data.connected;
                    alert(`RK3588连接测试结果:\n连接状态: ${connected ? '[在线]' : '[离线]'}\nTCP服务器: ${data.tcp_server_running ? '[运行中]' : '[停止]'}\n服务器时间: ${data.server_time}`);
                })
                .catch(e => {
                    alert('[错误] 连接测试失败: ' + e.message);
                });
        }
        
        function toggleFullscreen() {
            const videoContainer = document.querySelector('.video-container');
            if (document.fullscreenElement) {
                document.exitFullscreen();
            } else {
                videoContainer.requestFullscreen().catch(e => {
                    console.log('全屏模式不支持:', e);
                });
            }
        }
        
        // 初始化
        document.addEventListener('DOMContentLoaded', () => {
            console.log('[系统] RK3588视频流测试系统初始化');
            
            // 初始化图表
            setTimeout(initCharts, 500);
            
            // 启动时间更新
            updateTime();
            setInterval(updateTime, 1000);
            
            // 图表自适应
            window.addEventListener('resize', () => {
                Object.values(charts).forEach(chart => {
                    if (chart) chart.resize();
                });
            });
        });
    </script>
</body>
</html>